<template>
  <div>
    <vxe-grid ref="xTable" v-bind="gridOptions" @cell-dblclick="cellDBLClickEvent" highlight-hover-row>
      <template #toolbar_buttons>
        <vxe-button @click="insertEvent(insertRow)" status="primary">新增</vxe-button>
      </template>

      <template #operate="{ row }">
        <vxe-button type="text" transfer @click="editEvent(row)">
          <a-icon type="edit" />
        </vxe-button>
        <vxe-button type="text" transfer>
          <a-icon type="setting" />
          <template #dropdowns>
            <vxe-button type="text" content="删除" transfer @click="removeEvent(row)"></vxe-button>
            <vxe-button type="text" content="密码" transfer @click="setPassWordEvent(row)"></vxe-button>
          </template>
        </vxe-button>
      </template>
    </vxe-grid>

    <vxe-modal
      v-model="showEdit"
      :title="isModal"
      :width="modalWidth"
      min-width="600"
      min-height="300"
      :loading="submitLoading"
      :show-zoom="true"
      destroy-on-close>
      <template #default>
        <vxe-form
          :data="formData"
          :items="formItems"
          :rules="formRules"
          title-align="right"
          title-width="100"
          @submit="submitEvent">
        </vxe-form>
      </template>
    </vxe-modal>
  </div>
</template>

<script>

import { changePwd, deleteUser, userAdd, userEdit } from '@/api/system'
import { debounce } from 'lodash'

export default {
  name: 'LVxeTable',
  components: {},
  props: {
    roleOptions: {
      type: Array,
      default: null
    },
    gridOptions: {
      type: Object,
      default: null
    },
    insertRow: {
      type: Object,
      default: null
    }
  },

  data () {
    const checkPassWord = debounce(({ itemValue, rule, rules, data, property }) => {
      if (itemValue !== data.password) {
        return new Error('两次输入的密码不一样！')
      }
    }, 500) // 防抖
    return {
      modalWidth: 800,
      sexList: [
        { label: '女', value: '0' },
        { label: '男', value: '1' }
      ],
      fromButtons: {
        align: 'center',
        span: 24,
        titleAlign: 'left',
        itemRender: {
          name: '$buttons',
          children: [{ props: { disabled: false, type: 'submit', content: '保存', status: 'primary' } }, {
            props: {
              disabled: false,
              type: 'reset',
              content: '重置'
            }
          }]
        }
      },
      isModal: '',
      selectRow: null,
      showEdit: false,
      submitLoading: false,
      formData: {
        id: null,
        username: null,
        nickname: null,
        email: null,
        mobile: null,
        enabled: null,
        roleIds: []
      },
      formRules: {
        username: [
          { required: true, message: '请输入名称' }
        ],
        nickname: [
          { required: true, message: '请输入昵称' }
        ],
        mobile: [
          { required: true, message: '请输入手机号' }
        ],
        email: [
          { required: true, message: '请输入邮箱' }
        ],
        password: [
          { required: true, message: '请输入密码' }
        ],
        confirmPassword: [
          { required: true, message: '请输入密码' },
          { validator: checkPassWord }
        ]
      },
      formItems: []
    }
  },
  created () {
    this.initSelectOptions()
  },
  mounted () {
    // this.initSelectOptions()
  },
  methods: {
    initSelectOptions () {
      this.formItems = [
        {
          title: '用户信息',
          span: 24,
          titleAlign: 'left',
          titleWidth: 200
          // titlePrefix: { icon: 'fa fa-address-card-o' }
        },
        {
          field: 'username',
          title: '用户名',
          span: 12,
          visible: true,
          itemRender: { name: '$input', props: { placeholder: '请输入用户名', disabled: false, readonly: false } }
        },
        {
          field: 'nickname',
          title: '昵称',
          span: 12,
          visible: true,
          itemRender: { name: '$input', props: { placeholder: '请输入昵称', disabled: false, readonly: false } }
        },
        {
          field: 'mobile',
          title: '手机号',
          span: 12,
          visible: true,
          itemRender: { name: '$input', props: { placeholder: '请输入手机号', disabled: false, readonly: false } }
        },
        {
          field: 'email',
          title: '邮箱',
          span: 12,
          visible: true,
          itemRender: { name: '$input', props: { placeholder: '请输入邮箱', disabled: false, readonly: false } }
        },
        {
          field: 'enabled',
          title: '是否启用',
          span: 12,
          visible: true,
          itemRender: {
            name: '$switch',
            props: {
              disabled: false,
              openLabel: '启用',
              openValue: true,
              closeLabel: '禁用',
              closeValue: false,
              readonly: false
            }
          }
        },
        {
          title: '用户权限',
          span: 24,
          titleAlign: 'left',
          titleWidth: 200
          // titlePrefix: { icon: 'fa fa-address-card-o' }
        },
        {
          field: 'roleIds',
          title: '角色',
          span: 24,
          visible: true,
          itemRender: {
            name: '$select',
            props: { multiple: true, disabled: false },
            options: this.roleOptions,
            readonly: false
          }
        }
      ]
      this.formItems.push(this.fromButtons)
    },
    formatterSex ({ cellValue }) {
      const item = this.sexList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    visibleMethod ({ data }) {
      return data.flag1 === 'Y'
    },
    isClickModal (isModal) {
      switch (isModal) {
        case '新增':
          this.isModal = isModal
          break
        case '编辑' :
          this.isModal = isModal
          break
        case '修改密码' :
          this.isModal = isModal
          break
        case '查看' :
          this.isModal = isModal
          break
        default:
          this.isModal = ''
      }
    },
    cellDBLClickEvent ({ row }) {
      for (var item of this.formItems) {
        if (item?.itemRender?.props !== undefined) {
          item.itemRender.props.disabled = true
          // console.log(item.itemRender.props)
        } else if (item?.itemRender?.children !== undefined) {
          item.itemRender.children.map((item) => {
            item.props.disabled = true
          })
        }
      }
      this.isClickModal('查看')
      this.showEdit = true
      // this.editEvent(row)
    },
    insertEvent () {
      this.initSelectOptions()
      this.formData = {
        username: '',
        nickname: '',
        email: '',
        mobile: '',
        roleIds: [],
        enabled: true
      }
      this.isClickModal('新增')
      this.selectRow = null
      this.showEdit = true
      // this.$XModal.message({ content: this.showEdit, status: 'info' })
      // console.log(this.showEdit)
    },
    editEvent (row) {
      // console.log(row)
      this.initSelectOptions()
      for (var item of this.formItems) {
        if (item?.field === 'username') {
          item.itemRender.props.disabled = true
          // console.log(item.itemRender.props)
        }
      }
      this.formData = {
        id: row.id,
        username: row.username,
        nickname: row.nickName,
        email: row.email,
        mobile: row.mobile,
        roleIds: row.roleIds,
        enabled: row.enabled
      }
      console.log('editEvent', this.formData)
      this.isClickModal('编辑')
      this.selectRow = row
      this.showEdit = true
      // console.log(this.showEdit)
    },
    removeEvent (row) {
      console.log('removeEvent', JSON.stringify(row))
      this.$XModal.confirm('您确定要删除该数据?').then(type => {
        const $table = this.$refs.xTable
        if (type === 'confirm') {
          deleteUser(row).then(res => {
            // console.log(res.data)
            const resData = res.data
            if (resData.code === 200) {
              // console.log(resData)
              $table.remove(row)
            }
          })
        }
      })
    },
    setPassWordEvent (row) {
      this.modalWidth = 600
      this.formItems = [
        {
          field: 'username',
          title: '用户名',
          span: 24,
          itemRender: { name: '$input', props: { placeholder: '请输入名称', disabled: true } }
        },
        {
          field: 'password',
          title: '密码',
          span: 24,
          itemRender: {
            name: '$input',
            props: { placeholder: '请输入密码', disabled: false, type: 'password', clearable: true }
          }
        },
        {
          field: 'confirmPassword',
          title: '确认密码',
          span: 24,
          itemRender: {
            name: '$input',
            props: { placeholder: '请重新输入密码', disabled: false, type: 'password', clearable: true }
          }
        },
        this.fromButtons
      ]
      this.formData = {
        id: row.id,
        username: row.username,
        password: ''
      }
      console.log('setPassWordEvent', this.formData)
      this.isClickModal('修改密码')
      this.selectRow = row
      this.showEdit = true
    },

    userAddOrUserEdit (parameter) {
      if (this.isModal === '编辑') {
        console.log('UserEdit', parameter)
        return userEdit(parameter)
      } else if (this.isModal === '新增') {
        console.log('userAdd', parameter)
        return userAdd(parameter)
      } else if (this.isModal === '修改密码') {
        return changePwd(parameter)
      }
    },
    submitEvent () {
      this.submitLoading = true
      console.log('submitEvent', this.formData)
      this.userAddOrUserEdit(JSON.stringify(this.formData)).then((res) => {
        console.log(res)
        const resData = res.data
        console.log('resData', resData)
        if (resData.code === 200) {
          const $table = this.$refs.xTable
          this.submitLoading = false
          this.showEdit = false
          if (this.isModal === '编辑') {
            this.$XModal.message({ content: '编辑成功', status: 'success' })
            Object.assign(this.selectRow, this.formData)
          } else if (this.isModal === '新增') {
            console.log('insertformData', this.formData)
            this.$XModal.message({ content: '新增成功', status: 'success' })
            $table.insert(this.formData)
          } else if (this.isModal === '修改密码') {
            console.log('修改密码', this.formData)
            this.$XModal.message({ content: '密码修改成功,请重新登录！', status: 'success', duration: 4000 })
          }
        } else if (resData.code >= 400) {
          throw resData
        }
      }).catch((error) => {
        // console.log(error)
        const message = error.response ? error.response.data.message : error.message
        // console.log(message)
        this.submitLoading = false
        // this.showEdit = false
        this.$XModal.message({ content: message, status: 'error' })
      })
    }
  }
}

</script>

<style scoped>
</style>
